//
//  CityListVC.m
//  FreeReading
//
//  Created by lanou3g on 15/10/29.
//  Copyright © 2015年 lanou3g. All rights reserved.
//

#import "CityListVC.h"
#import "CityModel.h"
#import "NSString+Characters.h"

@interface CityListVC () <UISearchResultsUpdating>

// 存放数据容器
@property (nonatomic, strong) NSMutableDictionary *dataDict;
// 存放key
@property (nonatomic, strong) NSMutableArray *dataArray;
// 搜索数组
@property (nonatomic, strong) NSMutableArray *searchArray;
// 搜索
@property (nonatomic, strong) UISearchController *searchController;

@end

@implementation CityListVC

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setSubviews];
    [self addSearchController];
    [HUDHeaper addHUDProgressInView:self.view text:@"加载中..."];
    [self loadData];
    
    
}
#pragma mark - 处理数据
- (void)loadData
{
    
    // 判断网络状态
    AFNetworkReachabilityManager *net_manager = [AFNetworkReachabilityManager sharedManager];
    [net_manager startMonitoring];
    [net_manager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        
        if (status == AFNetworkReachabilityStatusUnknown || status == AFNetworkReachabilityStatusNotReachable) {
            UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:@"网络异常 请检查网络后再试" preferredStyle:(UIAlertControllerStyleAlert)];
            UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
                return ;
                
            }];
            
            [alert addAction:action];
            [self presentViewController:alert animated:YES completion:nil];
        }
        
        
    }];
    
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/html",@"text/json",@"text/javascript", nil];
    [manager GET:kCityListUrl parameters:nil success:^(AFHTTPRequestOperation * _Nonnull operation, id  _Nonnull responseObject) {
        
        NSDictionary *dataDic = responseObject[@"data"];
        
        // 解析数据
        // 解析所有城市数据
        NSArray *citiesArray = dataDic[@"cities"];
        for (NSDictionary *dic in citiesArray) {
            
            NSString *key = dic[@"letter"];
            NSMutableArray *value = [self.dataDict valueForKey:key];
            if (value == nil) {
                value = [NSMutableArray array];
            }
            
            CityModel *model = [[CityModel alloc] init];
            [model setValuesForKeysWithDictionary:dic];
            
            [value addObject:model];
            
            [self.dataDict setObject:value forKey:key];
            
        }
    
        // 解析热门城市
        NSArray *hot_cities = dataDic[@"hot_cities"];
        NSMutableArray *tempArray = [NSMutableArray array];
        for (NSDictionary *dic in hot_cities) {
            
            CityModel *model = [[CityModel alloc] init];
            [model setValuesForKeysWithDictionary:dic];
            [tempArray addObject:model];
        }
        [self.dataDict setObject:tempArray forKey:@"#"];
        
        // 取出所有的key排序
        self.dataArray = [NSMutableArray arrayWithArray:[self.dataDict.allKeys sortedArrayUsingSelector:@selector(compare:)]];
      
        [HUDHeaper hideAllHUDsForView:self.view animated:YES];
        
        // 刷新tableView
        [self.tableView reloadData];
        
    } failure:^(AFHTTPRequestOperation * _Nullable operation, NSError * _Nonnull error) {
       
        
        NSString *message = [NSString stringWithFormat:@"%@", [error localizedDescription]];
        
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:message preferredStyle:(UIAlertControllerStyleAlert)];
        UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
            return ;
        }];
        
        [alert addAction:action];
        
        [self presentViewController:alert animated:YES completion:nil];
        
        
    }];
    
}
// 移除searchController 避免延迟消失影响效果
- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
    if (self.searchController.active) {
        self.searchController.active = NO;
        [self.searchController.searchBar removeFromSuperview];
    }
}
// 设置UI
- (void)setSubviews
{
    self.view.backgroundColor = [UIColor whiteColor];
   
    // titleView
    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 100, 30)];
    titleLabel.textAlignment = NSTextAlignmentCenter;
    titleLabel.text = @"请选择您所在的城市";
    titleLabel.textColor = [UIColor whiteColor];
    self.navigationItem.titleView = titleLabel;
    // UIBarButtonItem
    UIBarButtonItem *leftbarButton = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"iconfont-arrowleft"] style:(UIBarButtonItemStylePlain) target:self action:@selector(back:)];
    self.navigationItem.leftBarButtonItem = leftbarButton;
    
}

// 添加searchController
- (void)addSearchController
{
    self.searchController = [[UISearchController alloc] initWithSearchResultsController:nil];
    // 设置代理
    self.searchController.searchResultsUpdater = self;
    self.searchController.dimsBackgroundDuringPresentation = NO;
    // 搜索时不隐藏导航条
    self.searchController.hidesNavigationBarDuringPresentation = NO;
    [self.searchController.searchBar sizeToFit];
    self.searchController.searchBar.frame = CGRectMake(0, 0, kScreenWidth, 50);
    // 添加表头
    self.tableView.tableHeaderView = self.searchController.searchBar;
    self.searchController.searchBar.placeholder = @"我在这...";
    
}
#pragma mark - 返回上一页
- (void)back:(UIBarButtonItem *)button
{
    if ([EnjoyDataManager shareManager].cityCode == nil) {
        
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:@"请选择城市" preferredStyle:(UIAlertControllerStyleAlert)];
        UIAlertAction *action = [UIAlertAction actionWithTitle:@"知道了" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
            [alert dismissViewControllerAnimated:YES completion:nil];
            return ;
        }];
        [alert addAction:action];
        [self presentViewController:alert animated:YES completion:nil];
    }
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - 内存警告
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
    if ([self isViewLoaded] && self.view.window == nil) {
        
        self.view = nil;
    }
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    if (self.searchController.active) {
        
        return 1;
    } {
    return self.dataDict.count;
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    if (self.searchController.active) {
        
        return self.searchArray.count;
        
    } else {
   NSString *key = self.dataArray[section];
    
    return [self.dataDict[key] count];
        
    }
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    NSString *key = self.dataArray[indexPath.section];
    
    static NSString *identifier = @"CityListCell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (cell == nil) {
        
        cell = [[UITableViewCell alloc] initWithStyle:(UITableViewCellStyleDefault) reuseIdentifier:identifier];
    }
    
    if (self.searchController.active) {
        CityModel *model = self.searchArray[indexPath.row];
        cell.textLabel.text = model.city_name;

    } else {
    
    CityModel *model = self.dataDict[key][indexPath.row];
    cell.textLabel.text = model.city_name;

    }
    return cell;
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    if (self.searchController.active) {
        
        return @"搜索结果";
    } else {
    if (section == 0) {
        return @"热门城市";
    } else {
        
    return self.dataArray[section];
        
    }
        
    }

}

-(NSArray<NSString *> *)sectionIndexTitlesForTableView:(UITableView *)tableView
{
    if (self.searchController.active) {
        return nil;
    } else {
    return self.dataArray;
    }
}

#pragma mark - cell点击方法
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    static CityModel *model = nil;
    if (self.searchController.active) {
        model = self.searchArray[indexPath.row];
        
    } else {
    NSString *key = self.dataArray[indexPath.section];
       model = self.dataDict[key][indexPath.row];
        
    }
    [EnjoyDataManager shareManager].cityName = model.city_name;
    [EnjoyDataManager shareManager].cityCode = model.city_code;
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - searchController 代理方法
- (void)updateSearchResultsForSearchController:(UISearchController *)searchController
{
    // 每次搜索都要清除搜索结果数组
    [self.searchArray removeAllObjects];
    NSString *filterString = searchController.searchBar.text;
    if (![filterString isEqualToString:@""]) {
        NSString *firstLetter = [filterString firstCharacterOfName];
        NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF contains [c] %@", firstLetter];
        NSMutableArray *tempArray = [NSMutableArray arrayWithArray:[self.dataArray filteredArrayUsingPredicate:predicate]];
        NSString *key = tempArray.firstObject;
        NSArray *value = self.dataDict[key];
        
        for (CityModel *model in value) {
            if ([model.city_name containsString:filterString]) {
                
                [self.searchArray addObject:model];
            }
        }
        
    }
    
    [self.tableView reloadData];
}

#pragma mark - 懒加载方法

-(NSMutableDictionary *)dataDict
{
    if (_dataDict == nil) {
        
        _dataDict = [NSMutableDictionary dictionary];
    }
    
    return _dataDict;
}

-(NSMutableArray *)dataArray
{
    if (_dataArray == nil) {
        
        _dataArray = [NSMutableArray array];

    }
    return _dataArray;
}

-(NSMutableArray *)searchArray
{
    if (!_searchArray) {
        
        _searchArray = [NSMutableArray array];
    }
    return _searchArray;
}
@end
